import datetime
import json
import logging
import os
import time
import allure
import pytest
import requests
from pytest_assume.plugin import assume

from utils.tools import remove_千分位

DEFAULT_TIMEOUT = 3333
class Common(object):

    def __init__(self, page=None):
        self.page = page
        self.baseurl = "http://cost.test.tmeoa.com"
        self.end_wait = 500

    def getcwd(self, file):
        '''获取上上级目录,并在其下增加文件夹file'''
        files = os.path.join(os.getcwd(), file)
        if not os.path.exists(files):
            os.mkdir(files)
        return files

    def goto_url(self, url):
        try:
            with allure.step(f"跳转到:{url}"):
                logging.error(f"  {url}跳转url")
            self.page.goto(url=url, timeout=DEFAULT_TIMEOUT)
            self.page.wait_for_load_state(state='networkidle', timeout=DEFAULT_TIMEOUT)
        except Exception as e:
            self.screenshot()


    def locator(self, element, frame=None):
        if frame is None:
            self.page.locator(element)
        else:
            self.page.frame_locator(frame).locator(element)

    def type(self, element, value, frame=None):
        try:
            with allure.step(f"输入:{value}"):
                self.wait_for_selector(element, frame)
                if frame is None:
                    self.page.locator(element).type(selector=value,no_wait_after=True,timeout=DEFAULT_TIMEOUT)
                else:
                    self.page.frame_locator(frame).locator(element).type(selector=value,no_wait_after=True,timeout=DEFAULT_TIMEOUT)

                self.press('html', 'Enter', frame)
        except Exception as e:
            logging.error(f"  输入值{value}报错:{e}  ")
            self.screenshot()
        else:
            logging.info(f"  输入值:{value}  ")

    def input(self, element, value, frame=None):
        with allure.step(f"输入:{value}"):
            logging.info(f"  输入值:{value}  ")
        try:
            self.wait_for_selector(element, frame)

            if frame is None:
                self.page.fill(element, '', no_wait_after=True, timeout=DEFAULT_TIMEOUT)
                self.wait_for_timeout(5)
                self.page.fill(element, value, no_wait_after=True, timeout=DEFAULT_TIMEOUT)
            else:
                self.page.frame(frame).fill(element, '', no_wait_after=True, timeout=DEFAULT_TIMEOUT)
                self.wait_for_timeout(5)
                self.page.frame(frame).fill(element, value, no_wait_after=True, timeout=DEFAULT_TIMEOUT)
            self.wait_for_timeout(10)
            self.press('body', 'Enter', frame)
        except Exception as e:
            logging.error(f"  输入值{value}报错:{e}  ")

    def click(self, element, frame=None):
        try:
            with allure.step(f"点击:{element}"):
                logging.info(f"  点击元素:{element}  ")
            self.wait_for_selector(element, frame)
            if frame is None:
                self.page.click(element, no_wait_after=True, timeout=DEFAULT_TIMEOUT)
            else:
                self.page.frame(frame).click(element, no_wait_after=True, timeout=DEFAULT_TIMEOUT)
            self.wait_for_timeout(5)
        except Exception as e:
            logging.error(f"  点击元素{element}报错:{e}  ")

    def dblclick(self, element, frame=None):
        try:
            with allure.step(f"双击:{element}"):
                logging.info(f"  【双击】元素:{element}  ")
            self.wait_for_selector(element, frame)
            if frame is None:
                self.page.dblclick(element, no_wait_after=True, timeout=DEFAULT_TIMEOUT)
            else:
                self.page.frame(frame).dblclick(element, no_wait_after=True, timeout=DEFAULT_TIMEOUT)
        except Exception as e:
            logging.error(f"  【双击】元素{element}报错:{e}  ")
            self.screenshot()

    def hover(self, element, frame=None):
        try:
            with allure.step(f"悬浮到:{element}"):
                logging.info(f'悬浮到{element}')
            self.wait_for_selector(element, frame)
            if frame is None:
                self.page.hover(element, timeout=DEFAULT_TIMEOUT)
            else:
                self.page.frame(frame).hover(element, timeout=DEFAULT_TIMEOUT)
        except Exception as e:
            logging.error(e)
            self.screenshot()

    def press(self, element, key, frame=None):
        try:
            self.wait_for_selector(element, frame)
            if frame is None:
                self.page.press(element, key,no_wait_after=True,timeout=DEFAULT_TIMEOUT)
            else:
                self.page.frame(frame).press(element, key,no_wait_after=True, timeout=DEFAULT_TIMEOUT)
        except Exception as e:
            self.screenshot()
            logging.error(e)

    def inner_text(self, element, frame=None):
        try:
            self.wait_for_selector(element, frame)
            if frame is None:
                text = self.page.inner_text(element, timeout=DEFAULT_TIMEOUT)
            else:
                text = self.page.frame(frame).inner_text(element, timeout=DEFAULT_TIMEOUT)
            return text
        except:
            logging.error(Exception)

    def assert_not_equal(self, element, text, isFloat=False, frame=None):
        try:
            actual = self.inner_text(element, frame)
        except:
            logging.error(Exception)
        finally:
            with allure.step(f"断言实际结果【{actual}】是否**不**等于预期结果【{text}】"):
                with assume:
                    if isFloat:
                        assert str(remove_千分位(text)) != str(remove_千分位(actual))
                    else:
                        assert str(text) not in str(actual)
            self.wait_for_timeout(100)
            self.screenshot()

    def assert_text(self, element, text, isFloat=False, frame=None):
        try:
            self.wait_for_timeout(500)
            self.wait_for_selector(element)
        except Exception as e:
            logging.error(e)
        finally:
            actual = self.inner_text(element, frame)
            with allure.step(f"断言实际结果【{actual}】是否等于预期结果【{text}】"):
                self.screenshot()
                with assume:
                    if isFloat:
                        assert str(remove_千分位(text)) in str(remove_千分位(actual))
                    else:
                        assert str(text) in str(actual)
            self.wait_for_timeout(200)


    def assert_element_not_exist(self, element, frame=None):
        """
                断言元素是否存在
                :param element:
                :param jietu:
                """
        global flag
        try:
            self.page.wait_for_selector(element, timeout=DEFAULT_TIMEOUT)
            flag = False
        except Exception as e:
            logging.error(e)
            flag = True
        finally:
            with allure.step(f"断言元素【{element}】不存在"):
                with assume:
                    assert flag
            self.screenshot()

    def screenshot(self):
        # path = '/Users/admin/data/testpic/{}'.format(time.strftime('%m%d', time.localtime(time.time())))
        # # path = os.path.join(os.path.join(os.getcwd(), '../../picture'), f"{time.strftime('%m%d', time.localtime(time.time()))}")
        # isExists = os.path.exists(path)
        # if not isExists:
        #     os.makedirs(path)
        # file = path + '/' + '<{}>'.format('测试') + time.strftime('%H%M%S',
        #                                                            time.localtime(time.time())) + '.png'
        with allure.step(f"🪞截图时间:{time.strftime('%H:%M:%S',time.localtime(time.time()))}🪞"):
            allure.attach(self.page.screenshot(animations="disabled", timeout=5000), '🪞测试截图🪞', allure.attachment_type.PNG)

    @allure.step('输入——附件上传')
    def input_upload_files(self, element, files):
        try:
            self.wait_for_selector(element)
            self.page.set_input_files(element, files, no_wait_after=True)
            self.wait_for_timeout(300)
            logging.info("附件上传成功")
        except Exception as e:
            logging.error(f"附件上传失败{e} ")

    @allure.step('点击——附件上传')
    def click_upload_files(self, element, files, frame=None):
        try:
            self.wait_for_selector(element)
            with self.page.expect_file_chooser(timeout=DEFAULT_TIMEOUT) as fc_info:
                self.click(element, frame)
            file_chooser = fc_info.value
            file_chooser.set_files(files, no_wait_after=True)
            self.wait_for_timeout(200)
            logging.info("附件上传成功")
        except Exception as e:
            logging.error(f"附件上传失败{e} ")

    def localtime_加减n天(self, n):
        today = datetime.datetime.now()
        offset = datetime.timedelta(days=n)
        re_date = (today + offset).strftime('%Y-%m-%d')
        return re_date

    def wait_for_timeout(self, value=2 * 1000):
        self.page.wait_for_timeout(value)


    def wait_for_selector(self, element, frame=None):
        try:
            if frame is None:
                self.page.wait_for_selector(element, timeout=DEFAULT_TIMEOUT)
                self.page.wait_for_load_state(state='networkidle', timeout=DEFAULT_TIMEOUT)
            else:
                self.page.frame(frame).wait_for_selector(element,timeout=DEFAULT_TIMEOUT)
        except Exception as e:
            logging.error(e)

    def scroll_into_view_if_needed(self, element, frame=None):
        try:
            if frame is None:
                self.page.locator(element).scroll_into_view_if_needed()
            else:
                self.page.frame_locator(frame).locator(element).scroll_into_view_if_needed()
        except Exception as e:
            logging.error(e)

    def page_close(self):
        with allure.step("关闭网页"):
            self.page.close()

    def browser_close(self):
        with allure.step("关闭浏览器"):
            self.context.close()

    def nowdate(self):
        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


class HttpClient:

    def __init__(self,cookies_dict=None):
        self.session = requests.Session()
        if cookies_dict is not None:
            for value in cookies_dict:
                requests.utils.cookiejar_from_dict(value)

    def send_request(self,method,url,data,params_type='JSON',headers=None,**kwargs):
        #请求方式转成大写
        method = method.upper()
        #参数类型转成大写
        params_type = params_type.upper()
        # data = json.dumps(eval(data))
        #判断post还是get
        if method == 'GET':
            response = self.session.request(method=method,url=url,params=data,headers=headers,**kwargs)
        elif method == 'POST':
            if params_type == 'FROM':
                response = self.session.request(method='POST',url=url,data=data,headers=headers,**kwargs)
            else:
                response = self.session.request(method='POST', url=url, json=data, headers=headers,**kwargs)
        return response

